package com.wnhz.work.jy.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.solidfire.gson.Gson;
import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.fragment.AlipayBean;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.alipay.PayResult;
import com.wnhz.work.jy.utils.alipay.SignUtils;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

/**
 * 充值
 */
public class TopUpActivity extends BaseActivity implements View.OnClickListener, TextWatcher {
    private static final String TAG = "TopUpActivity";
    private int way = 0;//0支付宝 1微信
    private TextView title;
    private TextView my_assets;//可用金额
    private TextView consume;//手续费
    private TextView account_money;//到账金额

    private EditText money_ed;

    private ImageView iv_pay_zhi;//支付宝
    private ImageView iv_pay_wei;//微信

    private String money;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_top_up);
        initTirle();

        initView();

        initClick();
        money_ed.addTextChangedListener(this);
//        setPayType();
        my_assets.setText(MyApplication.getInstance().userBean.getSum()+"元");
    }

    private void initClick() {
        findViewById(R.id.rl_zhi).setOnClickListener(this);
//        findViewById(R.id.rl_wei).setOnClickListener(this);
        findViewById(R.id.btn).setOnClickListener(this);
    }

    private void initView() {
        iv_pay_zhi = (ImageView) findViewById(R.id.iv_pay_zhi);
        iv_pay_wei = (ImageView) findViewById(R.id.iv_pay_wei);

        my_assets = (TextView) findViewById(R.id.my_assets);
        consume = (TextView) findViewById(R.id.consume);
        account_money = (TextView) findViewById(R.id.account_money);

        money_ed = (EditText) findViewById(R.id.money_ed);

        iv_pay_zhi.setImageResource(R.mipmap.ic_xuanze31_li);
    }

    private void initTirle() {
        title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("订金");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        title.setFocusable(true);
        title.setFocusableInTouchMode(true);
        title.requestFocus();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.rl_zhi:
                way = 0;
                iv_pay_zhi.setImageResource(R.mipmap.ic_xuanze31_li);
//                setPayType();
                break;
           /* case R.id.rl_wei:
                way = 1;
                setPayType();
                break;*/

            //充值
            case R.id.btn:
                if (money == null || "".equals(money)){
                    MyToast("请输入金额");
                }else if (Integer.parseInt(money) == 0){
                    MyToast("请输入金额");
                }else {
                    post();
                }

                break;
        }
    }

    private void post() {
        Map<String,Object> map = new HashMap<>();

        map.put("userId",MyApplication.getInstance().userBean.getUserId());
        map.put("money",money);
        showDialog();
        XUtil.Post(ConfigUtil.RECHARGE,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: "+result);
                try {
                    JSONObject json = new JSONObject(result);
                    String re = json.optString("result");
                    String info = json.optString("info");

                    if ("1".equals(re)){
                        AlipayBean bean = new AlipayBean();
                        bean = new Gson().fromJson(info,AlipayBean.class);
                        Log.e(TAG, "onSuccess: "+bean.toString());
                        setset(bean);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Log.e(TAG, "onError: "+ex );
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }
        });
    }

    private void setPayType() {
        if (way == 0){
            iv_pay_zhi.setImageResource(R.mipmap.ic_xuanze31_li);
            iv_pay_wei.setImageResource(R.mipmap.ic_xuanze_nor);
        }else if (way == 1){
            iv_pay_wei.setImageResource(R.mipmap.ic_xuanze31_li);
            iv_pay_zhi.setImageResource(R.mipmap.ic_xuanze_nor);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        money = money_ed.getText().toString();
        if (money.length() > 0){
            account_money.setText(money+"元");
        }else {
            account_money.setText("0.00元");
        }
        consume.setText("0.00元");
    }



    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(TopUpActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        MyApplication.getInstance().upUser();
                        finish();

                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）

                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    /**
     * get the sdk version. 获取SDK版本号
     */
    public void getSDKVersion() {
        PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();
        Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
    }




    /**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     */
    private String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }


    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    private void setset(AlipayBean alipayBean) {

        String orderInfo = getOrderInfo3(alipayBean);
        // String orderInfo = alipayBean.getStr();
        /**
         * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
         */
        String sign = alipayBean.getSign();
		/*String sign = sign(orderInfo);
		try {
			*//**
         * 仅需对sign 做URL编码
         *//*
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}*/
        /**
         * 完整的符合支付宝参数规范的订单信息
         */
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {

                // 构造PayTask 对象
                PayTask alipay = new PayTask(TopUpActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);


                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private String getOrderInfo3(AlipayBean alipayBean) {
        // 服务接口名称， 固定值 mobile.securitypay.pay
        // 参数编码， 固定值
        String orderInfo = "_input_charset=\"utf-8\"";
        // 商品详情
        orderInfo += "&body=" + "\"" + alipayBean.getBody() + "\"";
        // 服务器异步通知页面路径-----TODO 修改异步通知的地址
        orderInfo += "&notify_url=" + "\"" + alipayBean.getNotify_url() + "\"";
        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + alipayBean.getOut_trade_no()
                + "\"";
        // 签约合作者身份ID
        orderInfo += "&partner=" + "\"" + alipayBean.getPartner() + "\"";
        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";
        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + alipayBean.getSeller_id() + "\"";

        orderInfo += "&service=\"mobile.securitypay.pay\"";
        // 商品名称
        orderInfo += "&subject=" + "\"" + alipayBean.getSubject() + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + alipayBean.getTotal_fee() + "\"";

        return orderInfo;
    }
}
